package okw.network;
import java.sql.Time;
import java.util.ArrayList;
import java.util.LinkedList;

import okw.database.DatabaseManager;
import okw.gui.MainWindowO;

import core.messages.Ack;
import core.messages.VoteMsg;


public class Queue2 {
	LinkedList<QueueItem> lista = new LinkedList<QueueItem>();

    public synchronized void put(QueueItem e){
    	lista.add(e);
        System.out.println("Dodano wiadomosc do kolejki przechowujacej");
        notify();
    }
    
    // szuka niewyslanych
    public synchronized ArrayList<QueueItem> findToSend(){
    	if ( (lista.size() == 0 ))
    		return null;
    	ArrayList<QueueItem> wynik = new ArrayList<QueueItem>();
    	Time time = new Time(System.currentTimeMillis());
    	for(QueueItem e: lista){
    		// sprawdza czas i ustawia nowy czas
    		if(e.getTime().getTime()+5000<time.getTime()){
    			System.out.println("Ponownie do wyslania " + e.getTime().getTime() + " " + time.getTime());
    			e.setTime(time);
    			wynik.add(e);
    		}	
    	}
    	return wynik;
    }
    
    // szuka elementu do usuniecia, gdy otrzymano potwierdzenie
    public synchronized boolean findToRemove(Ack msg){
        if ( (lista.size() == 0 ))
        	return false;
    	for(QueueItem e: lista){
    		if(msg.getReceived()==e.getMsg().getNumber()){
    			if(msg.getInfoNr() == 1){
    				DatabaseManager db = DatabaseManager.getInstance();
    				VoteMsg paczka = (VoteMsg)e.getMsg();
    				db.setVotesPackageAsSend(paczka.getVotesPackageCore().getName());
    			} else if(msg.getInfoNr() == 3) {
    				DatabaseManager db = DatabaseManager.getInstance();
    				VoteMsg paczka = (VoteMsg)e.getMsg();
    				db.setSummaryPackageAsSend(paczka.getSummaryPackageCore().getElectionName());
    				MainWindowO.infoOKoncu();
    			}
    			lista.remove(e);
    			System.out.println("Usunieto wiadomosc z kolejki przechowujacej");
    			return true;
    		}
    	}
		return false;
        
    }
        			

}